from pathlib import Path

from langchain_community.document_loaders import JSONLoader
from langchain_community.document_loaders import PyPDFLoader, CSVLoader
from langchain_core.documents import Document

from app.common.result import Result
from app.exception.biz_exception import BizException
from app.models.file_dto import FileDTO


def read_csv(path: Path) -> list[Document]:
    csv_loader = CSVLoader(path)
    return csv_loader.load()


def read_pdf(path: Path) -> list[Document]:
    """
    PDF内容读取器
    :param path: PDF文件路径
    :return: list[Document]
    """
    pdf_loader = PyPDFLoader(path)
    return pdf_loader.load()


def read_json(path: Path) -> list[Document]:
    """
    JSON文件内容加载
    :param path:
    :return:
    """
    json_loader = JSONLoader(path, jq_schema='.messages[]',
                             content_key="content",
                             text_content=False, metadata_func=json_meta_func)
    return json_loader.load()


def read_txt(path: Path) -> Result:
    return Result.ok()


def read_md(path: Path) -> Result:
    return Result.ok()


reader_type_mapping = {
    'CSV': read_csv,
    'PDF': read_pdf,
    'TXT': read_txt,
    'MD': read_md,
    'JSON': read_json,
}


def reader_file(file_dto: FileDTO) -> Result[list[Document]]:
    """
    读取文件内容
    :param file_dto:文件DTO
    :return:
    """
    file_extension_name = file_dto.file_extension_name
    if file_extension_name is None:
        raise BizException(msg="文件扩展名不存在", code=-1)
    loader = reader_type_mapping.get(file_extension_name.upper())
    document = loader(file_dto.file_path)
    return Result.ok(document)


def json_meta_func(record: dict, metadata: dict) -> dict:
    """
    metadata 元数据解析
    :param record: json数据记录
    :param metadata: 行metadata
    :return: metadata
    """
    metadata["keyword"] = record.get("keyword")
    metadata["title"] = record.get("title")
    metadata["author"] = record.get("author")
    metadata["date"] = record.get("date")
    metadata["summary"] = record.get("summary")
    return metadata
